package cn.kzgg.basic.service.impl;

import cn.kzgg.basic.constants.BaseConstant;
import cn.kzgg.basic.dto.LoginDto;
import cn.kzgg.basic.dto.WeChatDto;
import cn.kzgg.basic.exception.BusinessException;
import cn.kzgg.basic.jwt.JwtUtils;
import cn.kzgg.basic.jwt.LoginResult;
import cn.kzgg.basic.jwt.RsaUtils;
import cn.kzgg.basic.service.ILoginService;
import cn.kzgg.basic.util.AjaxResult;
import cn.kzgg.basic.util.HttpClientUtils;
import cn.kzgg.basic.util.MD5Utils;
import cn.kzgg.basic.util.StrUtils;
import cn.kzgg.system.domain.Menu;
import cn.kzgg.system.domain.Permission;
import cn.kzgg.system.mapper.MenuMapper;
import cn.kzgg.system.mapper.PermissionMapper;
import cn.kzgg.user.domain.Logininfo;
import cn.kzgg.user.domain.User;
import cn.kzgg.user.domain.Wxuser;
import cn.kzgg.user.mapper.LogininfoMapper;
import cn.kzgg.user.mapper.UserMapper;
import cn.kzgg.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.kzgg.basic.jwt.JwtUtils.generateTokenExpireInSeconds;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;



    /**
     * 管理员登录
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> loginAccount(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();

        //1.校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空");
        }
        //2.根据username+type查loginfo，username，password，email三个字段
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        //2.1.查询不到loginfo就报错，说明没有这个账户
        if (logininfo == null) {
            throw new BusinessException("没有这个账户");
        }
        //2.2.查询到了，确认密码是否一致
        String salt = logininfo.getSalt();//加密的盐值
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);//密码+盐值
        //,不一致，报错，一致就登录成功
        if (!md5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误，请重新输入");
        }
        /*//3.存储redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES

        );
        //4.返回token+loginfo
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        logininfo.setPassword(null);
        logininfo.setSalt(null);


        return map;*/

        //3.登录成功
        return loginSuccessHandler(logininfo);
    }

    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //1.判断logininfo是否是员工
        if(logininfo.getType()==0){
            //是员工就获取他的权限
            //获取menu权限
            List<Menu> menus = menuMapper.LoadMenusByLogininfoId(logininfo.getId());
            //获取permission权限
            List<String> permissions =permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            //将菜单权限和按钮权限保存到loginResult对象
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //2.将登陆人信息和权限加密成jwt串传到前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用私钥将loginResult对象加密成jwt串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 300);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        map.put("logininfo",logininfo);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("menus",loginResult.getMenus());//为了防止没有报空指针，所以在LoginResult设置
        map.put("permissions",loginResult.getPermissions());


        return map;
    }

    /**
     * 微信三方扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        //1.从dto中获取code进行非空判断
        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("code不能为空");
        }
        //2.通过code从微信中获取token+openid
        //2.1.通过TOKEN_URL：.replace：APPID、SECRET、CODE
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID",BaseConstant.WeChatConstants.APPID)
                .replace("SECRET",BaseConstant.WeChatConstants.SECRET)
                .replace("CODE",code);
        //2.2.使用HttpClientUtils工具类获得token字符串
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        //2.3.将token字符串转换为token对象
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        //2.4.用token对象获取账号密码(這是要返回前端binder.html的)
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
        //3.通过openid查询t_wxuser表，获取wxuser对象，判断wxuser是否存在且userid是否为空
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //3.1.如果wxuser存在且user_id不为空，说明是第二次登录
        if(wxuser!=null && wxuser.getUserId()!=null){
            //3.1.查出对应的logininfo
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            /*//3.2.存储redis
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
            //3.3.返回token+logininfo(map,AjaxResult)--注意过滤掉敏感信息，不要返回给前端
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.show().setResultObj(map);*/
            return AjaxResult.show().setResultObj(loginSuccessHandler(logininfo));
        }
        //3.2.没有的话就应该让浏览器跳转至绑定页面，用户设置账号密码来完成绑定，返回token+openid
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.show().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 第一次绑定
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(WeChatDto dto) {
        //1.根据username判断是否曾经有t_user
        User user = userMapper.loadByPhone(dto.getPhone());
        //1.1存在查出来等着绑定
        Logininfo logininfo = null;
        if(user!=null){
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else {
            //1.2不存在，生成新的t_user和t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            //根据logininfo的id新增user
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //2.根据token和openid从微信获取用户基本信息
        //2.1.通过WXUSER_URL：.replace:ACCESS_TOKE、OPENID
        String wxUserURL = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        //2.2.使用HttpClientUtils工具类
        // 获得wxUser字符串
        String wxUserStr = HttpClientUtils.httpGet(wxUserURL);
        //3.根据微信用户的基本信息将wxUser字符串转换为wxuser对象
        Wxuser wxUser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        //4.t_wxuser绑定t_user
        wxUser.setUserId(user.getId());
        //5.保存t_wxuser----完成了整个绑定流程
        wxuserMapper.save(wxUser);
        /*//6.储存redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        //7.返回token+logininfo(map,AjaxResult)--注意过滤掉敏感信息，不要返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        return map;*/
        return loginSuccessHandler(logininfo);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(WeChatDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }


}
